package jp.yishii.microbridgesample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MicrobridgeSampleActivity extends Activity implements OnClickListener
{
	static final int TCP_PORT = 60101;
	static final String LOG_TAG = "MicrobridgeSample";
	boolean mSocketActive = true;
	boolean mLedState = false;
	ToggleButton mLedButton;
	private ServerSocket mServerSocket;
	private Socket mSock = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mLedButton = (ToggleButton)findViewById(R.id.ledButton);
        mLedButton.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();

        mLedButton.setChecked(false);
        mLedState = false;

        mSocketActive = true;
        
    	new Thread(runnable).start();
        Toast.makeText(this,"Server thread start",Toast.LENGTH_SHORT).show();
    }
	
    @Override
    public void onPause() {
    	super.onPause();
    	
    	mSocketActive = false;
    	try {
    		if(mSock != null){
    			mSock.close();
   		}
        	mServerSocket.close();
    		Log.v("MicrobridgeSamle","Socket closed");
    	} catch (IOException e){
    		Log.v("MicrobridgeSamle","IOException");
    	}
    }
    
	private Runnable runnable = new Runnable()
	{
        String str;

        public void run()
		{
			try {
				mServerSocket = new ServerSocket();
				mServerSocket.setReuseAddress(true);
				mServerSocket.bind(new InetSocketAddress(TCP_PORT));

				while(mSocketActive){
					Log.v(LOG_TAG,"Waiting to connect...");
					mSock = mServerSocket.accept();
					BufferedReader mReceivedData =
							new BufferedReader(
									new InputStreamReader(
											mSock.getInputStream()));
		            OutputStreamWriter mTransmit = new OutputStreamWriter(
		            		mSock.getOutputStream());
		
	                while(mSocketActive && (str = mReceivedData.readLine()) != null){
	                    System.out.println("Command = " + str);
	 
	                    if("get".equals(str)){
	                    	Log.v(LOG_TAG,"RetrieveCommand received");
	                    	mTransmit.write(mLedState ? 0x30 : 0x31);
	                    	mTransmit.flush();
	                    }
	                    //else if("quit".equals(str)){
	                    //	mSocketActive = false;
	                    //}
	                }
	
					mSock.close();
					mSock = null;
				}
				mServerSocket.close();
				Log.v(LOG_TAG,"Socket closed");
			
			} catch (IOException e1) {
				e1.printStackTrace();
				System.exit(-1);
			}
		}
	};

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.ledButton){
			if(mLedButton.isChecked() == true){
				Log.v(LOG_TAG,"Led -> ON");
				mLedState = true;
			} else {
				Log.v(LOG_TAG,"Led -> OFF");
				mLedState = false;
			}
		}
	}
}
